<template>
  <view class="content">
    <tui-form ref="formRef" :show-message="false" :model="formData">
      <!-- 单位工程 -->
      <tui-form-item arrow labelWidth='180' asterisk label="单位工程" prop="unitProject" @click="popupShow=true">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.unitProject"
          placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-bottom-popup :zIndex="1002" :height="600" :maskZIndex="1001" :show="popupShow" @close="popupShow=false">
        <tui-cascade-selection height="200px" :defaultItemList='defaultItemList' :itemList="itemList"
          @complete="complete"></tui-cascade-selection>
      </tui-bottom-popup>

      <!-- 分部工程 -->
      <tui-form-item arrow labelWidth='180' asterisk label="分部工程" prop="subsection" @click="popupShow2=true">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.subsection"
          placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-bottom-popup :zIndex="1002" :height="600" :maskZIndex="1001" :show="popupShow2" @close="popupShow2=false">
        <tui-cascade-selection height="200px" :defaultItemList='defaultItemLists' :itemList="itemList2"
          @complete="complete2"></tui-cascade-selection>
      </tui-bottom-popup>
      <tui-form-item labelWidth='180' asterisk label="验收编号" prop="subsectionCode">
        <tui-input padding="0" :borderBottom="false" v-model="formData.subsectionCode" placeholder="请输入"></tui-input>
      </tui-form-item>
	  <tui-form-item labelWidth='180' asterisk label="子分部工程数" prop="tenderSubsectionQuantity">
	    <tui-input padding="0" :disabled="true" :borderBottom="false" v-model="formData.tenderSubsectionQuantity" placeholder="请输入"></tui-input>
	  </tui-form-item>
      <tui-form-item labelWidth='180' asterisk label="分项工程数" prop="branchQuantity">
        <tui-input padding="0" :disabled="true" type='number' :borderBottom="false" v-model="formData.branchQuantity"
          placeholder="请输入"></tui-input>
      </tui-form-item>
      <!-- 验收日期 -->
      <tui-form-item arrow labelWidth='180' asterisk label="验收日期" prop="checkDate" @click="openCalendar">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.checkDate"
          placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-calendar ref="calendar" :initStartDate="initStartDate" :initEndDate="initEndDate" lunar isFixed :type="2"
        @change="changeCalendar"></tui-calendar>
        <tui-form-item labelWidth='180' asterisk label="质量控制资料" prop="controlData">
          <tui-input padding="0" :borderBottom="false" v-model="formData.controlData" placeholder="请输入"></tui-input>
        </tui-form-item>
        <tui-form-item labelWidth='180' asterisk label="安全和功能检验" prop="safetyFunctional">
          <tui-input padding="0" :borderBottom="false" v-model="formData.safetyFunctional" placeholder="请输入"></tui-input>
        </tui-form-item>
        <tui-form-item labelWidth='180' asterisk label="观感质量" prop="appearance">
          <tui-input padding="0" :borderBottom="false" v-model="formData.appearance" placeholder="请输入"></tui-input>
        </tui-form-item>
      <tui-form-item labelWidth='180' asterisk label="备注" prop="memo">
        <tui-input padding="0" :borderBottom="false" v-model="formData.memo" placeholder="请输入"></tui-input>
      </tui-form-item>
      <tui-section title="选择未分部验收子分部工程信息" is-line background="#f8f8f8"></tui-section>
      <tui-no-data v-if="checkboxItems.length===0" :fixed="false" imgUrl="/static/img_nodata.png">暂无数据</tui-no-data>
      <tui-checkbox-group @change="checkBoxChange">
        <tui-label v-for="(item,index) in checkboxItems" :key="index">
          <tui-list-cell>
            <view class="thorui-align__center">
              <tui-checkbox :checked="item.checked" :value="item.value" color="#f8683c" borderColor="#999"
                style="margin-right: 20px;"></tui-checkbox>
              <view style="display: flex;flex-direction: column;">
                <view>{{item.tenderSubsectionName}}</view>
                <view>【分项工程数】{{item.branchQuantity}}</view>
              </view>
            </view>
          </tui-list-cell>
        </tui-label>
      </tui-checkbox-group>
      <view style="padding:0 10px 10px 10px;">
        <tui-form-button text="提交" @click="submit"></tui-form-button>
      </view>
      
    </tui-form>
  </view>
</template>

<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, onMounted } from 'vue';
 import {
 	getProjectTenderSubsectionNoCheckedList,
 	getFullProjectSubsectionInfo,
 	reStartProjectSubsectionProcess,
 	updateProjectSubsection,
 	startProjectSubsectionProcess,
 	addProjectSubsection,
 	getProjectUnitProjectManageList,
 	getSysSubsectionManageList,
 	} from '@/apis/subsection.js';
  const popupShow = ref(false)
  const popupShow2 = ref(false)
  const itemList = ref([])
  const itemList2 = ref([])
  const formRef = ref(null);
  const calendar = ref(null);
  const defaultItemList = ref([])
  const defaultItemLists = ref([])

  const rules = [
    {
      name: "unitProject",
      rule: ["required"],
      msg: ["请选择单位工程"]
    }, {
      name: "subsection",
      rule: ["required"],
      msg: ["请选择分部工程"]
    }, {
      name: "subsectionCode",
      rule: ["required"],
      msg: ["请输入分部验收编号"]
    }, {
      name: "branchQuantity",
      rule: ["required", 'isNum'],
      msg: ["请输入分项工程数", '请输入数字']
    }, {
      name: "tenderSubsectionQuantity",
      rule: ["required", 'isNum'],
      msg: ["请输入子分部工程数", '请输入数字']
    }, {
      name: "checkDate",
      rule: ["required"],
      msg: ["请选择验收日期"]
    }, {
      name: "controlData",
      rule: ["required"],
      msg: ["请输入质量控制资料"]
    },
    {
      name: "safetyFunctional",
      rule: ["required"],
      msg: ["请输入安全和功能检验"]
    },
    {
      name: "appearance",
      rule: ["required"],
      msg: ["请输入观感质量"]
    },{
      name: "memo",
      rule: ["required"],
      msg: ["请输入备注"]
    }];

  const formData = ref({
    unitProject: '',
    subsection: '',
    subsectionCode: "",
	tenderSubsectionQuantity:0,
    branchQuantity: 0,
    checkEndDate: "",
    checkStartDate: "",
    controlData:'',
    safetyFunctional:'',
    appearance:'',
    memo: "",
    projectTenderSubsectionViewRespList: [],
    subAndUnitProjectIds: [],
    sysSubsectionIds: [],
    checkDate: ''
  })

  const projectId = uni.getStorageSync('projectInfo').id
  const isEdit = ref(false)
  const subsectionid = ref(0)
  const checkboxItems = ref([])
  const initEndDate = ref('')
  const initStartDate = ref('')

  onMounted(() => {
    getList()
  });

  onLoad(({ subsectionId }) => {
    //   //如果有lotId就是编辑状态 再次提交时发起重新送审
    //   //添加一个状态判断编辑还是新增
    isEdit.value = false
    if (subsectionId) {
      subsectionid.value = subsectionId
      isEdit.value = true
      getFullProjectSubsectionInfo(subsectionId).then(res => {
        console.log(res.data.data);
        let data = res.data.data
        formData.value = data
        formData.value.unitProject = data.unitProjectName + '-' + data.subUnitProjectName
        formData.value.subAndUnitProjectIds = [data.unitProjectId, data.subUnitProjectId]
        formData.value.subsection = data.subsectionName
        formData.value.sysSubsectionIds = [data.subsectionId]
        setTimeout(() => {
          defaultItemList.value = [data.unitProjectName, data.subUnitProjectName]
          defaultItemLists.value = [data.subsectionName]
        }, 100)


        initStartDate.value = data.checkStartDate
        initEndDate.value = data.checkEndDate
        formData.value.checkDate = data.checkStartDate + ' 至 ' + data.checkEndDate

        getProjectTenderSubsectionNoCheckedList(projectId, data.subsectionId).then(res => {
          console.log(res.data.data);
          let arr = data.projectTenderSubsectionViewRespList.map(e => e.projectTenderSubsectionId)
          checkboxItems.value = res.data.data.map(e => ({ ...e, checked: arr.includes(e.projectTenderSubsectionId) ? true : false, value: '' + e.projectTenderSubsectionId }))
          formData.value.projectTenderSubsectionViewRespList = data.projectTenderSubsectionViewRespList
        })
      })
    }
  })

  const checkBoxChange = (e) => {
    formData.value.projectTenderSubsectionViewRespList = checkboxItems.value.filter((item) => e.detail.value.includes(item.value));
  }

  //单位工程
  const complete = (e) => {
    formData.value.unitProject = e.result.map(e => e.text).join('-')
    formData.value.subAndUnitProjectIds = e.result.map(e => e.value)
    popupShow.value = false
  }


  //分部工程
  const complete2 = (e) => {
    console.log(e);
    formData.value.subsection = e.result.map(e => e.text).join('-')
    formData.value.sysSubsectionIds = e.result.map(e => e.value)
    getProjectTenderSubsectionNoCheckedList(projectId, e.result[0].value).then(res => {
      checkboxItems.value = res.data.data.map(e => ({ ...e, checked: false, value: '' + e.projectTenderSubsectionId}))
      formData.value.tenderSubsectionQuantity=res.data.data.length
      formData.value.branchQuantity=res.data.data.reduce((a,c)=>a+c.branchQuantity,0)
    })
    popupShow2.value = false
  }

  //验收日期
  const openCalendar = () => {
    calendar.value.show()
  }

  const changeCalendar = (e) => {
    formData.value.checkDate = e.startDate + ' 至 ' + e.endDate
    formData.value.checkStartDate = e.startDate
    formData.value.checkEndDate = e.endDate
  }

  let maxDepth=0

  // 获取列表数据
  const getList = () => {
      getProjectUnitProjectManageList(projectId).then(res => {
          itemList.value = handleData(res.data.data, 1);
      });
      
      getSysSubsectionManageList().then(res => {
          itemList2.value = handleData(res.data.data, 2);
      });
  }


  // 转换格式
  const handleData = (data, depth) => {
      if (depth > maxDepth) {
          maxDepth = depth;
      }
  	if (depth > 2) {
  	        return null;
  	} 
      return data.map(item => ({
          text: item.nodeName,
          value: item.id,
          children: item.children ? handleData(item.children, depth + 1) : null
      }));
  }


  //提交表单
  const submit = async (values) => {
    if (isEdit.value === false) {
      //新增
      if (formRef.value) {
        formRef.value.validate(formData.value, rules, true).then((res) => {
          if (res.isPass && formData.value.projectTenderSubsectionViewRespList.length>0) {
            addProjectSubsection(projectId, formData.value).then(res => {
              startProjectSubsectionProcess(res.data.data).then(res => {
                if (res.data.code === 200) {
                  uni.navigateTo({
                    url: '/pages/subsection/subsection'
                  })
                }
              })
            })
          }else{
            plus.nativeUI.toast('请选择未子分部验收分项工程信息')
          }
        })
      }
    } else {


      //编辑
      if (formRef.value) {
        formRef.value.validate(formData.value, rules, true).then((res) => {
          if (res.isPass && formData.value.projectTenderSubsectionViewRespList.length>0) {
            updateProjectSubsection(formData.value).then(res => {
              reStartProjectSubsectionProcess(subsectionid.value).then(res => {
                if (res.data.code === 200) {
                  uni.navigateTo({
                    url: '/pages/subsection/subsection'
                  })
                }
              })
            })
          }else{
            plus.nativeUI.toast('请选择未子分部验收分项工程信息')
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    background-color: #fff;

    // padding: 0px 10px 10px 10px;
    .thorui-align__center {
      display: flex;
      align-items: center;
    }

    .tui-text {
      font-size: 30rpx;
      padding-left: 12rpx;
    }

    .container {
      height: 100vh;
      background-color: #eeeeee;

      .formClass {
        padding: 0 20rpx;
        display: flex;
        flex-direction: column;
      }
    }
  }
</style>